package com.civ.sensor.dht.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;

public class HttpClient4yeeLink {
	private static String encoding = "GBK";
	public static String tdPoint = "382793";
	public static String hdPoint = "382794";

	public void execute(int data,String dPoint) {
		try {
			Socket s = new Socket("api.yeelink.net", 80);
			OutputStreamWriter osw = new OutputStreamWriter(s.getOutputStream());
			StringBuffer sb = new StringBuffer();
			String currentDate = new DateUtils().getCurrentDateTimeStr();
			currentDate = currentDate.replace(" ", "T");
			String dataObj = "{\"timestamp\":\""+currentDate+"\",\"value\":"+data+"}";
			//String header = "POST /v1.0/device/344390/sensor/"+point+"/datapoint HTTP/1.1\r\n";
			sb.append("POST /v1.0/device/344390/sensor/"+dPoint+"/datapoint HTTP/1.1\r\n");
			sb.append("Host:api.yeelink.net\r\n");
			sb.append("Connection:Keep-Alive\r\n");
			sb.append("Content-Type:application/json\r\n");
			sb.append("Content-Length:"+dataObj.length()+"\r\n");
			sb.append("Connection:Keep-Alive\r\n");
			sb.append("U-ApiKey:3ba7e05d5af41d34de0417d69fae2f6d\r\n");
			
			// 注，这是关键的关键，忘了这里让我搞了半个小时。这里一定要一个回车换行，表示消息头完，不然服务器会等
			sb.append("\r\n");
			
				osw.write(sb.append(dataObj).toString());
				osw.flush();

				// --输出服务器传回的消息的头信息
				InputStream is = s.getInputStream();

				BufferedReader br = new BufferedReader(new InputStreamReader(is));

				String tmp = "";
				while ((tmp = br.readLine()) != null) {
					System.out.println(tmp);
				}
				//打印输出
				System.out.println(sb);
				br.close();
				is.close();
			

			

		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static String readLine(InputStream is, int contentLe) throws IOException {
		ArrayList lineByteList = new ArrayList();
		byte readByte;
		int total = 0;
		if (contentLe != 0) {
			do {
				readByte = (byte) is.read();
				lineByteList.add(Byte.valueOf(readByte));
				total++;
			} while (total < contentLe);// 消息体读还未读完
		} else {
			do {
				readByte = (byte) is.read();
				lineByteList.add(Byte.valueOf(readByte));
			} while (readByte != 10);
		}

		byte[] tmpByteArr = new byte[lineByteList.size()];
		for (int i = 0; i < lineByteList.size(); i++) {
			tmpByteArr[i] = ((Byte) lineByteList.get(i)).byteValue();
		}
		lineByteList.clear();

		return new String(tmpByteArr, encoding);
	}
}
